package com.app.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.DepartmentService;
import com.app.service.PersonService;
import com.app.service.RoleService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.StringTool;
import com.app.util.TokenUtils;
import com.app.vo.DepartmentVo;
import com.app.vo.RoleVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@Controller
@RequestMapping("/api/dep")
public class DepartmentController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PersonService personService;

    @GetMapping("/getDepTree")//部门管理树
    public Result<Object> getDepTree( String name,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idsList = departmentService.getDepId(user.getDepartmentId());
        List<DepartmentModel> modelFirList = departmentService.selectDepTree(name, idsList);//拿到当前账号下的部门List
        List<PersonModel> personModelList = personService.listExport();
        if (modelFirList == null) {
            return Result.error(200, "暂无数据");
        }
        int pid = 100;
        for (int i = 0; i < modelFirList.size(); i++) {
            List<Integer> numList = departmentIds(modelFirList.get(i), modelFirList);
            int menu = 0;
            for (int j = 0; j < personModelList.size(); j++) {
                if (numList.contains(personModelList.get(j).getDepartmentId())) {
                    menu += 1;
                }
            }
            modelFirList.get(i).setPersonNum(menu);
            if (modelFirList.get(i).getStatus() == 1) {
                modelFirList.get(i).setStatusText("正常");
            } else {
                modelFirList.get(i).setStatusText("隐藏");
            }
            //确认第一级菜单
            if (modelFirList.get(i).getPid() < pid) {
                pid = modelFirList.get(i).getPid();
            }
        }
        return Result.success(findChildren(modelFirList, pid));
    }

    private List<Integer> departmentIds(DepartmentModel model, List<DepartmentModel> modelFirList) {
        List<Integer> ids = new ArrayList<>();
        ids.add(model.getId());
        List<DepartmentModel> sonList = new ArrayList<>();
        for (int i = 0; i < modelFirList.size(); i++) {
            if (modelFirList.get(i).getPid().equals(model.getId())) {
                sonList.add(modelFirList.get(i));
            }
        }
        if (sonList.size() > 0) {
            for (int j = 0; j < sonList.size(); j++) {
                ids.addAll(departmentIds(sonList.get(j), modelFirList));
            }
        }
        return ids;
    }

    //递归查询方法
    private List<DepartmentModel> findChildren(List<DepartmentModel> modelList, Integer pid) {
        List<DepartmentModel> departmentModelList = new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            if (modelList.get(i).getPid().equals(pid)) {
                DepartmentModel model = modelList.get(i);
                List<DepartmentModel> modelList1 = findChildren(modelList, model.getId());
                for (int j = 0; j < modelList1.size(); j++) {
                    model.setChild(modelList1);
                }
                departmentModelList.add(model);
            }
        }
        return departmentModelList;

    }

    @GetMapping("/getDepList")//部门管理分页查询
    public Result<Object> getDepList(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String shortName,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<DepartmentModel> depModelPage = departmentService.getPageDepList(page, limit, name, shortName);
        if (depModelPage == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) depModelPage.getTotal();
        List<DepartmentModel> depModelList;
        depModelList = depModelPage.getRecords();
        DepartmentVo vo = new DepartmentVo();
        vo.setCount(count);
        vo.setList(depModelList);
        return Result.success(vo);
    }


    @PostMapping("/insertDep")//    新增/修改部门管理
    public Result<Object> addAndUpdateDep(@RequestBody DepartmentModel departmentModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        if (departmentModel.getId() > 0) {
            if (StrUtil.isNotBlank(departmentModel.getPersonName())) {
                DepartmentModel depByDepId = departmentService.getDepByDepId(departmentModel.getId());
                depByDepId.setPersonName(departmentModel.getPersonName());
                depByDepId.setUpdateTime(CommonHelp.getNowTimestamp());
                departmentService.update(depByDepId);
            }else {
                departmentModel.setUpdateTime(CommonHelp.getNowTimestamp());
                departmentService.update(departmentModel);
            }
        } else {
            DepartmentModel model = departmentService.getDepLevelByPId(departmentModel.getPid());//根据pid取id
            if (model != null) {
                departmentModel.setPid(model.getId());
                departmentModel.setCreateTime(CommonHelp.getNowTimestamp());
                departmentService.insert(departmentModel);
            }else {
                departmentModel.setCreateTime(CommonHelp.getNowTimestamp());
                departmentService.insert(departmentModel);
            }
        }
        return Result.success("操作成功");
    }

    @GetMapping("/updateDepStatus")//修改部门状态
    public Result<Object> updateStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        DepartmentModel model = new DepartmentModel();
        model.setId(id);
        model.setStatus(status);
        departmentService.update(model);
        List<DepartmentModel> departmentModelList = departmentService.getListByPid(id);
        if (departmentModelList == null && departmentModelList.size() > 0) {
            return Result.success(null);
        }
        for (int i = 0; i < departmentModelList.size(); i++) {
            DepartmentModel depModel = new DepartmentModel();
            depModel.setId(departmentModelList.get(i).getId());
            depModel.setStatus(status);
            departmentService.update(depModel);
        }
        return Result.success(null);
    }

    @GetMapping("/selectDepById")//单查部门
    public Result<Object> selectDepById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        DepartmentModel depModel = departmentService.getDepByDepId(id);
        if (depModel == null) {
            return Result.error(500, "该部门不存在");
        } else {
            return Result.success(depModel);
        }
    }

    @GetMapping("/deleteDep")//删除基层单位
    public Result<Object> deleteDep(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
//        DepartmentModel departmentModel = departmentService.getDepByDepId(id);
//        if(departmentModel.getLevel() != 3){
//            return Result.error(500,"删除基层单位以外的部门请联系管理员删除");
//        }
        departmentService.delete(id);
        return Result.success(null);
    }

    @GetMapping("/selectDep")//删除基层单位
    public Result<Object> selectDep() {
        return Result.success( departmentService.selectDep());
    }


}
